package com.algorithm.dp;

import java.util.ArrayList;
import java.util.List;

/**
 * 完全背包:指背包中同一种物品可以有无数件
 */
public class CompletePack {
    //第一种解决方案:
    //  假设无数件物品是使用 2^k (k从1增长到 2^k*w[k] < w(背包))为止
    //  将其转化为01简单背包
    public static void main(String[] args) {
        int packSize = 100;
        int[] weights = {0,  33, 40, 57};
        int[] values = {0,  63, 47, 85};
        completePack02(packSize, weights, values);
    }

    public static void completePack01(int packSize, int[] weights, int[] values) {
        List<Integer> forkWeightList = new ArrayList<>();
        forkWeightList.add(0);
        List<Integer> forkValueList = new ArrayList<>();
        forkValueList.add(0);
        for (int i = 1; i < weights.length; i++) {
            split(packSize, weights[i], values[i], forkWeightList, forkValueList);
        }

        SimplePack.pack01(forkWeightList.toArray(new Integer[forkWeightList.size()]),forkValueList.toArray(new Integer[forkValueList.size()]),packSize);
    }

    /**
     *@author : daniel.yang
     *@date : 2018/11/6
     *@desc : 拆分无穷个物品为n个
     *@param packSize :
     *@param weight :
     *@param value :
     *@param forkWeightList :
     *@param forkValueList :
     */
    private static void split(int packSize, int weight, int value, List<Integer> forkWeightList, List<Integer> forkValueList) {
        int n = 0;
        int currentWeight = (int) (weight * Math.pow(2, n));
        int currentValue = (int) (value * Math.pow(2, n));
        // 多重背包 currentWeight <= weight * maxItemNums
        while (currentWeight <= packSize) {
            forkWeightList.add(currentWeight);
            forkValueList.add(currentValue);
            n++;
            currentWeight = (int) (weight * Math.pow(2, n));
            currentValue = (int) (value * Math.pow(2, n));
        }
    }

    /**
     *@author : daniel.yang
     *@date : 2018/11/6
     *@desc : 第二种方式,将其看作01背包的变种:f[i][j] = max{f[i-1][j], f[i][j-weight[i]] }
     *@param packSize :
     *@param weights :
     *@param values :
     */
    public static void  completePack02(int packSize, int[] weights, int[] values){
        Integer[] arr = new Integer[packSize+1];
        SimplePack.init(arr);
        for (int j = 1; j < weights.length; j++) {
            for (int i = 1; i < packSize; i++) {
                SimplePack.findMaxValue(values[j],arr,i,weights[j]);
            }
        }
        System.out.println("背包最大值:"+arr[packSize-1]);
    }


}
